<template>
    <el-container class="sys_account_set_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="queryData"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <div class="search_area">
                            <span class="label">到期日期</span>
                            <el-date-picker v-model="queryData.expired_date" type="daterange" placeholder="请选择日期"
                                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                            value-format="yyyy-MM-dd" style="width: 210px;"
                                            @change="getList(true)" />
                        </div>
                        <el-select v-model="queryData.state" clearable @change="getList(true)"
                                   style="width: 100px;margin-right: 5px;">
                            <el-option label="全部状态" value="" />
                            <el-option v-for="(item, index) in accountSetStateList" :key="index"
                                       :label="item.name" :value="item.code" />
                        </el-select>
                        <el-select v-model="queryData.version" clearable @change="getList(true)"
                                   style="width: 100px;margin-right: 5px;">
                            <el-option label="全部版本" value="" />
                            <el-option v-for="(item, index) in versionList" :key="index"
                                       :label="item.name" :value="item.value" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
            <component-dialog dialog-drag :options="componentDialogOption"
                              @closeEvent="handleCloseEvent" />
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import sysAccountSetApi from "@common/api/system/sysAccountSetApi";
import AccountSetForm from "../dialog/account-set/AccountSetForm";
import AccountSetResource from "../dialog/account-set/AccountSetResource";
import ResetAdmin from "../dialog/ResetAdmin";
import ResetAccountSet from "../dialog/account-set/ResetAccountSet";
import AccountSetSyncData from "../dialog/account-set/AccountSetSyncData";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "SysAccountSet",
    data() {
        let $this = this;
        return {
            versionList:[{name:"免费版",value:"free"},{name:"基础版",value:"basic"},{name:"专业版",value:"pro"},{name:"旗舰版",value:"ultimate"},],
            modeList: [],
            queryData: {
                state: '',
                version:'',
            },
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            $this.getList();
                        },
                    },
                    {
                        id: "add",
                        type: 'primary',
                        icon: "fa fa-plus",
                        show: true,
                        method: () => {
                            $this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        type: 'success',
                        icon: "fa fa-pencil",
                        show: true,
                        method: () => {
                            $this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "del",
                        type: 'danger',
                        icon: "fa fa-trash-o",
                        show: true,
                        method: () => {
                            $this.delAccountSet(null, 'batch');
                        },
                    },
                    {
                        id: "del",
                        type: 'success',
                        icon: "fa fa-refresh",
                        show: true,
                        method: () => {
                            $this.updateDb();
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: "编码" },
                    {
                        type: "select",
                        field: "state",
                        label: "状态",
                        options: [ { value: 0, label: "等待建库" }, { value: 1, label: "建库中" }, {
                            value: 2,
                            label: "运行中"
                        }, { value: -1, label: "建库失败" }, { value: -2, label: "已过期" } ]
                    },
                ],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: 'AccountSetTable',
                container: '.sys_account_set_container',
                multiSelect: true,
                checkboxConfig: {
                    visibleMethod({ row }) {
                        return !row.master;
                    },
                    checkMethod({ row }) {
                        return !row.master;
                    },
                },
                columns: [
                    {
                        label: '拥有者',
                        prop: 'owner_name',
                        align: 'center',
                        formatter: (row) => {
                            if (row.owner_name) {
                                return row.owner_name
                            } else {
                                return row.owner_sid
                            }
                        }
                    },
                    {
                        label: '编码',
                        prop: 'code',
                        align: 'center',
                    },
                    {
                        label: '数据库名称',
                        prop: 'db_name',
                        align: 'center',
                    },
                    {
                        label: '数据库驱动',
                        prop: 'driver',
                        align: 'center',
                    },
                    {
                        label: '数据访问url',
                        prop: 'db_url',
                        align: 'center',
                    },
                    {
                        label: '数据库用户名',
                        prop: 'db_user_name',
                        align: 'center',
                    },
                    {
                        label: '状态',
                        prop: 'state',
                        align: 'center',
                        width: 90,
                        formatter: (row) => {
                            let filter = $this.accountSetStateList.filter((item) => {
                                return item.code === row.state
                            });
                            if (filter.length > 0) {
                                if (row.state == -1 ){
                                    //如下写法无法将flyway_except显示完整
                                    return filter[0].name+"<br>"+row.flyway_except;
                                }else{
                                    return filter[0].name;
                                }
                            }
                            return row.state;
                        },
                    },
                    {
                        label: '用户数限制',
                        prop: 'uc_limit',
                        align: 'center',
                        width: 90,
                    },
                    {
                        label: '模块',
                        prop: 'mode',
                        align: 'center',
                        width: 90,
                        formatter(row) {
                            let modeStr = (row.mode || []).map(item => {
                                let filter = $this.modeList.filter(t => item === t.value);
                                if ($this.$utils.isNotEmptyList(filter)) {
                                    return filter[0].display_text;
                                }
                                return '主库';
                            });
                            return modeStr.join(',');
                        },
                    },
                    {
                        label: '版本',
                        prop: 'version',
                        align: 'center',
                        width: 90,
                        formatter: (row) => {
                            let filter = $this.versionList.filter((item) => {
                                return item.value === row.version
                            });
                            if (filter.length > 0) {
                                return filter[0].name;
                            }
                            return row.version;
                        },
                    },
                    {
                        label: '到期日期',
                        prop: 'expired_date',
                        align: 'center',
                        width: 130,
                    },
                    {
                        label: '备注',
                        prop: 'note_info',
                        align: 'center',
                        maxWidth: 200,
                    },
                ],
                operates: {
                    list: [
                        {
                            id: 'info',
                            icon: 'fa fa-pencil',
                            type: 'primary',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '编辑',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.openDialog(row, 'edit');
                            }
                        },
                        {
                            id: 'copy',
                            icon: 'fa fa-copy',
                            type: 'primary',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '复制',
                            },
                            filter(row) {
                                return row.master;
                            },
                            method: (index, row) => {
                                $this.openDialog(row, 'add');
                            }
                        },
                        {
                            id: 'auth',
                            icon: 'el-icon-key',
                            type: 'warning',
                            size: 'mini',
                            show: false,
                            tooltip: {
                                content: '授权',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.openAuthDialog(row);
                            }
                        },
                        {
                            id: 'reset_admin',
                            icon: 'el-icon-user',
                            type: 'warning',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '重置主账号',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.openResetAdmin(row);
                            }
                        },
                        {
                            id: 'test',
                            icon: 'el-icon-sort',
                            type: 'warning',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '测试连接',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.testConnection(row)
                            }
                        },
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            type: 'danger',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.delAccountSet(row)
                            }
                        },
                        {
                            id: 'reset',
                            icon: 'el-icon-refresh',
                            type: 'danger',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '重置数据库',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.create_db(row)
                            }
                        },
                        {
                            id: 'syncData',
                            icon: 'el-icon-right',
                            type: 'danger',
                            size: 'mini',
                            show: false,
                            tooltip: {
                                content: '同步参数数据',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.showSyncDataDialog(row)
                            }
                        },
                        {
                            id: 'updateDb',
                            icon: 'fa fa-refresh',
                            type: 'success',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '更新数据结构',
                            },
                            filter(row) {
                                return !row.master;
                            },
                            method: (index, row) => {
                                $this.updateDb(row)
                            }
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                }
            },
            componentDialogOption: {
                visible: false,
            },
        }
    },
    computed: {
        ...mapState('system', [ 'accountSetStateList' ]),
    },
    mounted() {
        this.initModeList();
        this.getList();
    },
    methods: {
        initModeList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindCommonParameterValuesByKey, {
                key1: 'account_mode',
            }).then(result => {
                _this.modeList = result.data || [];
            }).catch(() => {
            });
        },
        handleHeaderEvent(event) {
            let $this = this;
            $this.queryData = $.extend({}, $this.queryData, event.searchForm);
            if (event.type === "search") {
                $this.getList(true);
            } else if (event.type === "refresh") {
                $this.getList(true);
            }
        },
        getList(isFirst) {
            let $this = this;
            $this.dataList = [];
            if (isFirst) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.queryData);
            queryData.with_resource = '1';
            sysAccountSetApi.findSysAccountSets(queryData, result => {
                if (result.data) {
                    result.data.forEach(t => {
                        if (t.mode && t.mode.startsWith("[")) {
                            t.mode = JSON.parse(t.mode);
                        } else {
                            t.mode = [];
                        }
                    })
                }
                $this.dataList = result.data;
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            })
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        //新增/编辑
        openDialog(row, type) {
            let $this = this;
            let title = type === 'add' ? '创建' : '编辑';
            if (type === 'edit') {
                if (!row && !$this.checkSelection($this.selectionList)) {
                    return;
                }
                if (!row) {
                    row = $.extend({}, $this.selectionList[0]);
                }
            } else {
                row = {
                    mode: [],
                    state: 0,
                    db_host: row?row.db_host:'',
                    db_password:row?row.db_password : '',
                    db_port:row?row.db_port : '',
                    db_url:row?row.db_url : '',
                    db_user_name:row?row.db_user_name : '',
                    driver:row?row.driver : '',
                };
            }
            $this.openComponentDialog({
                title,
                width: '640px',
                component: AccountSetForm,
                propsData: {
                    row,
                    modeList: $this.modeList,
                },
                refresh: true,
            })
        },
        openAuthDialog(row) {
            let $this = this;
            $this.openComponentDialog({
                title: `资源授权:${ row.code } ${ row.owner_name ? row.owner_name : '' }`,
                width: '640px',
                component: AccountSetResource,
                propsData: {
                    account_set_sid: row.sid,
                },
            })
        },
        openResetAdmin(row) {
            let $this = this;
            $this.openComponentDialog({
                title: '重置账套的主账号',
                width: '400px',
                component: ResetAdmin,
                propsData: {
                    row,
                },
            })
        },
        //删除
        delAccountSet(row, type) {
            let $this = this;
            let ids = [];
            if (type === 'batch') {
                if ($this.selectionList.length === 0) {
                    $this.$message.error("请选中一条数据");
                    return;
                } else {
                    ids = $this.selectionList.map(item => item.sid);
                }
            } else {
                ids.push(row.sid);
            }
            $this.confirmDel(ids);
        },
        confirmDel(ids) {
            let $this = this;
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysAccountSetApi.delSysAccountSets({ sids: ids }, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                })
            })
            .catch(() => {
            });
        },
        create_db(row) {
            let $this = this;
            $this.openComponentDialog({
                title: '重置账套数据库',
                width: '400px',
                component: ResetAccountSet,
                propsData: {
                    row,
                },
            })
        },
        showSyncDataDialog(row) {
            let $this = this;
            $this.openComponentDialog({
                title: '同步数据',
                width: '500px',
                component: AccountSetSyncData,
                propsData: {
                    row,
                },
            })
        },
        testConnection(row) {
            let $this = this;
            sysAccountSetApi.testConnection({ sid: row.sid }, () => {
                $this.$message.success("连接成功");
            });
        },
        openComponentDialog(options) {
            const _this = this;
            _this.componentDialogOption = {
                visible: true,
                title: options.title,
                width: options.width,
                component: options.component,
                propsData: options.propsData,
                btns: [
                    {
                        type: 'primary',
                        text: '确定',
                        loading: true,
                        method(option, { component }) {
                            component && typeof component.confirm === 'function' && component.confirm().then(valid => {
                                if (valid) {
                                    option.visible = false;
                                    if (options.refresh) {
                                        _this.getList();
                                    }
                                }
                            })
                        },
                    }
                ],
            };
        },
        handleCloseEvent(component) {
            if (component.timeout_handler) {
                window.clearTimeout(component.timeout_handler);
            }
        },
        updateDb(row) {
            let $this = this;
            let sid_list = [];
            if (!row) {
                if (!$this.checkSelection($this.selectionList)) {
                    return;
                }
                sid_list = $this.selectionList.map(item => item.sid);
            } else {
                sid_list.push(row.sid);
            }
            $this.$confirm("是否执行更新数据结构？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                $this.fetchData($this.$api.API_ExecuteUpdateSchema, {
                    sid_list,
                }).then(() => {
                    $this.$message.success("执行更新成功");
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.sys_account_set_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .buttons {
        margin: 0 0 10px 0;
    }

    .ceshi {
        max-height: 500px !important;
        z-index: 1000;
    }
}
</style>
